var planet, fspp_alerting=false;
$(document).ready(function() {
  if ($('td[@bgcolor=#602020]').size() > 0) {
    return;
  }

  var p = $('body table:eq(2) tr td');

  planet = {
    levels_pp:  [0,5,8,11,17,25,38,57,86,128,192,288,433],

    id: parseInt(document.location.href.match(/[0-9]+$/)[0]),
    name: $(p.get(0)).html(),

    hf_lvl: parseInt($(p.get(10)).attr({id:'hf_lvl',nowrap:'nowrap'}).html()),
    hf_rmn: parseInt($(p.get(12)).attr({id:'hf_rmn',nowrap:'nowrap',align:'right'}).html()),
    rf_lvl: parseInt($(p.get(14)).attr({id:'rf_lvl',nowrap:'nowrap'}).html()),
    rf_rmn: parseInt($(p.get(16)).attr({id:'rf_rmn',nowrap:'nowrap',align:'right'}).html()),
    gc_lvl: parseInt($(p.get(18)).attr({id:'gc_lvl',nowrap:'nowrap'}).html()),
    gc_rmn: parseInt($(p.get(20)).attr({id:'gc_rmn',nowrap:'nowrap',align:'right'}).html()),
    rl_lvl: parseInt($(p.get(22)).attr({id:'rl_lvl',nowrap:'nowrap'}).html()),
    rl_rmn: parseInt($(p.get(24)).attr({id:'rl_rmn',nowrap:'nowrap',align:'right'}).html()),
    sb_lvl: parseInt($(p.get(26)).attr({id:'sb_lvl',nowrap:'nowrap'}).html()),
    sb_rmn: parseInt($(p.get(28)).attr({id:'sb_rmn',nowrap:'nowrap',align:'right'}).html()),

    pp: parseInt($(p.get(30)).attr('id', 'pp').html()),

    tr:     parseInt($(p.get(38)).attr({id:'tr_tt'}).html()),
    tr_val: parseInt($(p.get(40)).attr({id:'tr_rmn',align:'left'}).html().replace(/[0-9]+\/([0-9]+)/,'$1')),
    cs:     parseInt($(p.get(42)).attr({id:'cs_tt'}).html()),
    cs_val: parseInt($(p.get(44)).attr({id:'cs_rmn',align:'left'}).html().replace(/[0-9]+\/([0-9]+)/, '$1')),
    ds:     parseInt($(p.get(46)).attr({id:'ds_tt'}).html()),
    ds_val: parseInt($(p.get(48)).attr({id:'ds_rmn',align:'left'}).html().replace(/[0-9]+\/([0-9]+)/, '$1')),
    cr: 0,
    cr_val: 0,
    bs: 0,
    bs_val: 0,

    getRemain: function(item) {
      switch (item) {
        case 'hf': return this.hf_rmn;
        case 'rf': return this.rf_rmn;
        case 'gc': return this.gc_rmn;
        case 'rl': return this.rl_rmn;
        case 'sb': return this.sb_rmn;

        case 'tr': return this.tr_val;
        case 'cs': return this.cs_val;
        case 'ds': return this.ds_val;
        case 'cr': return this.cr_val;
        case 'bs': return this.bs_val;
      }
    },

    getLevel: function(item) {
      switch (item) {
        case 'hf': return this.hf_lvl;
        case 'rf': return this.rf_lvl;
        case 'gc': return this.gc_lvl;
        case 'rl': return this.rl_lvl;
        case 'sb': return this.sb_lvl;
      }
    },

    spend: function(item, pp) {
      if (!confirm('Do you really want spend '+pp+' points in '+item+'?')) return false;
      var _items = {
        'hf':'farm',
        'rf':'fabrik', 
        'gc':'kultur', 
        'rl':'forschungslabor', 
        'sb':'starbase', 
        'tr':'infantrieschiff', 
        'cs':'kolonieschiff', 
        'ds':'destroyer', 
        'cr':'cruiser', 
        'bs':'battleship'
      }

      $.post(
        '/0/Planets/submit.php',
        {points: pp, produktion: _items[item], i: this.id},
        function() {
          window.location.reload();
        }
      );
    }
  }

  $('#awplus_content table:eq(0) tr:gt(12) td:contains(Cruiser)').parent().find('td:eq(1), td:eq(3)').each(function(i) {
    switch(i) {
      case 0: planet.cr = parseInt($(this).attr({id:'cr_tt'}).text()); break;
      case 1: planet.cr_val = parseInt($(this).attr({id:'cr_rmn',align:'left'}).text().replace(/[0-9]+\/([0-9]+)/, '$1')); break;
    }
  });
  $('#awplus_content table:eq(0) tr:gt(12) td:contains(Battleship)').parent().find('td:eq(1), td:eq(3)').each(function(i) {
    switch(i) {
      case 0: planet.bs = parseInt($(this).attr({id:'bs_tt'}).text()); break;
      case 1: planet.bs_val = parseInt($(this).attr({id:'bs_rmn',align:'left'}).text().replace(/[0-9]+\/([0-9]+)/, '$1')); break;
    }
  });

  if (planet.pp <= 0) return this;

  // A brincadeira comeca aki!

  var items = ['hf','rf','gc','rl','sb'];

  for (i in items) {
    var item = items[i];
    $('#'+item+'_rmn').append('&nbsp; <span id="'+item+'_fspp" style="background-color: #404040; width: 10px; height: 10px;">&nbsp;&raquo;&nbsp;</span><span id="'+item+'_fsppv" class="fsppv" style="background-color: #404040;"></span>');

    if (_pos = findPos($('#'+item+'_fspp').get(0))) {
      var _css = {
        position: 'absolute',
        top: _pos.y -1,
        left: _pos.x - 1,
        border:"1px solid #1f1f1f",
        background: '#404040',
        cursor: 'pointer'
      }
    } else {
      var _css = {}
    }

    $('#'+item+'_fsppv').hide().css(_css).mouseout(
      function(e){
        var rel = e.relatedTarget;
        if (rel.className == 'fsppv' || rel.className == 'fsppva') { return; }
        $(this).hide();
      });

    $('#'+item+'_fspp').hover(
      function(){
        var item = $(this).attr('id').replace(/^(..).*/, '$1');
        if ($('#'+item+'_fsppv').html() != '') {
          $('#'+item+'_fsppv').show();
          return;
        }

        var _fsppv = $('#'+item+'_fsppv').html("&nbsp;&laquo;&nbsp; ");

        var _html;
          
        var spend_value = planet.getRemain(item);
        var level = planet.getLevel(item)+1;
        while (spend_value <= planet.pp) {
          _html = '<a id="fsppva_'+item+'_'+level+'" class="fsppva" href="javascript:void(0);" style="background-color: #b0cae2;">&nbsp;+'+level+'&nbsp;</a>';
          _fsppv.append(_html);
          eval('var fsppva_'+item+'_'+level+' = '+spend_value);
          // coloca o evento de click
          $('#fsppva_'+item+'_'+level).hover(
            function(){$(this).css('background-color', 'blue');}, 
            function(){$(this).css('background-color', '#b0cae2');}
          ).click(function(){
            var pp = eval($(this).attr('id'));
            planet.spend(item, pp);
          });

          //prepara o proximo passo...
          spend_value += planet.levels_pp[++level];
        }

        _html = '<a id="fsppva_'+item+'_all" class="fsppva" href="javascript:void(0);" style="background-color: red;">&nbsp;&lt;&lt;&nbsp;</a>';
        _fsppv.append(_html).show();
        $('#fsppva_'+item+'_all').click(function(){planet.spend(item, planet.pp)});
      }, 
      function(){ }
    );
  }


  // -- FLEETS -----------------------------------------------

  var items = ['tr','cs','ds','cr','bs'];

  for (i in items) {
    var item = items[i];
    var total = Math.floor( planet.pp / planet[item+'_val'] );
    var rmn = $('#'+item+'_rmn').append('&nbsp;(<span id="'+item+'_fspptt">'+total+'</span>)');
    if (total == 0) continue;

    rmn.append('&nbsp; <span id="'+item+'_fspp" style="cursor: pointer; background-color: #404040; width: 10px; height: 10px;">&nbsp;&raquo;&nbsp;</span><span id="'+item+'_fsppv" class="fsppv" style="background-color: #404040;"></span>');

    if (_pos = findPos($('#'+item+'_fspp').get(0))) {
      var _css = {
        position: 'absolute',
        top: _pos.y -1,
        left: _pos.x - 1,
        border:"1px solid #1f1f1f",
        background: '#404040',
        'cursor': 'pointer',
      }
    } else {
      var _css = {}
    }

    $('#'+item+'_fsppv').hide().css(_css);

    $('#'+item+'_fspp').click(function(){
        var item = $(this).attr('id').replace(/^(..).*/, '$1');
        if ($('#'+item+'_fsppv').html() != '') {
          $('#'+item+'_fsppv').show();
          $('#fsppva_'+item)[0].focus();
          return;
        }

        var _fsppv = $('#'+item+'_fsppv').html("&nbsp;&laquo;&nbsp; ").click(
          function() { $(this).hide(); }
        );

        var  _html = '<input type="text" id="fsppva_'+item+'" class="fsppva" style="font-size: 0.7em; width: 30px; border: 1px solid #000; margin: 1px 7px; background-color: #4A4A4A;" />';

        _fsppv.append(_html);

        $('#fsppva_'+item)
          .keyup(function(e) {
              this.value = this.value.replace(/[^0-9]+/g, '');
              var tt_fleets = parseInt(this.value == '' ? 0 : this.value);
              if (e.keyCode == 13 && !fspp_alerting && tt_fleets) {
                fspp_alerting = true;
                var item = this.id.replace(/^fsppva_(..)/, '$1');
                var pp = planet[item+'_val'] * tt_fleets;
                var total = parseInt($('#'+item+'_fspptt').html());

                if (tt_fleets > total) {
                  alert('Choose a value lower or equal than '+ total+'.');
                  this.value = '';
                  fspp_alerting = false;
                  return;
                }

                if (!planet.spend(item, pp)) return;

                this.disabled = true;
                $('#'+item+'_fsppv').hide();
              }
            })[0].focus(); 

        $('#'+item+'_fsppv').show();
        $('#fsppva_'+item)[0].focus();
      }
    );
  }

});
